package com.adinnet.admin.system.controller;



import com.adinnet.admin.common.service.CommonService;
import com.adinnet.admin.common.shiro.ShiroUtils;
import com.adinnet.admin.system.model.SysMenu;
import com.adinnet.admin.system.model.SysRole;
import com.adinnet.admin.system.service.SysMenuService;
import com.adinnet.admin.system.service.SysRoleMenuService;
import com.adinnet.admin.system.service.SysRoleService;
import com.adinnet.common.utils.JSONUtil;
import com.adinnet.common.utils.StringUtil;
import com.adinnet.core.BaseController;
import com.adinnet.core.JsonResult;
import com.adinnet.core.PageResult;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * <p>
 * 角色表 前端控制器
 * </p>
 *
 * @author sunjianbo
 * @since 2019-05-17
 */
@Controller
@RequestMapping("/sys/role")
public class SysRoleController extends BaseController {

    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private SysMenuService sysMenuService;
    @Autowired
    private SysRoleMenuService roleMenuService;
    @Autowired
    private CommonService commonService;

    @RequiresPermissions("role:view")
    @RequestMapping()
    public String role() {
        return "system/role.html";
    }

    @ResponseBody
    @RequestMapping("/buttonRole")
    public JsonResult buttonRole(String buttons) {
        JSONArray jsonArray = JSONObject.parseArray(buttons);
        Map<String, Object> map = new HashMap<>();
        map.put("userId", ShiroUtils.getLoginUserId().toString());
        map.put("buttons", jsonArray);
        List<String> buttonList = sysMenuService.buttonListByUserId(map);
        if (buttonList.size() > 0)
            return JsonResult.ok("有权限").put("data", buttonList);
        else
            return JsonResult.error("没有权限");
    }

    /**
     * 查询所有角色
     **/
    @RequiresPermissions("role:view")
    @ResponseBody
    @RequestMapping("/list")
    public PageResult<SysRole> list(String keyword) {
        List<SysRole> roleList = sysRoleService.list();
        if (StringUtils.isNotBlank(keyword)) {
            Iterator<SysRole> iterator = roleList.iterator();
            while (iterator.hasNext()) {
                SysRole next = iterator.next();
                if (!next.getRoleName().contains(keyword) && !next.getComments().contains(keyword)) {
                    iterator.remove();
                }
            }
        }
        return new PageResult<>(roleList);
    }

    /**
     * 添加角色
     **/
    @RequiresPermissions("role:update")
    @ResponseBody
    @RequestMapping("/add")
    public JsonResult add(SysRole role, HttpServletRequest request) {
        if (sysRoleService.save(role)) {
            commonService.saveOperation(request,"角色管理-添加");
            return ok("添加成功");
        } else {
            return error("添加失败");
        }
    }

    /**
     * 修改角色
     **/
    @RequiresPermissions("role:update")
    @ResponseBody
    @RequestMapping("/update")
    public JsonResult update(SysRole role,HttpServletRequest request) {
        if (sysRoleService.updateById(role)) {
            commonService.saveOperation(request,"角色管理-修改");
            return ok("修改成功");
        } else {
            return error("修改失败");
        }
    }

    /**
     * 删除角色
     **/
    @RequiresPermissions("role:update")
    @ResponseBody
    @RequestMapping("/delete")
    public JsonResult delete(Integer roleId,HttpServletRequest request) {
        SysRole sysRole=new SysRole();
        sysRole.setId(roleId);
        sysRole.setDeleted(true);
        if (sysRoleService.updateById(sysRole)) {
            commonService.saveOperation(request,"角色管理-修改");
            return ok("删除成功");
        }
        return error("删除失败");
    }

    /**
     * 角色权限树
     */
    @ResponseBody
    @GetMapping("/authTree")
    public List<Map<String, Object>> authTree(Integer roleId) {
        List<SysMenu> roleAuths = sysMenuService.listByRoleId(roleId);
        List<SysMenu> allAuths = sysMenuService.list();
        List<Map<String, Object>> authTrees = new ArrayList<>();
        for (SysMenu one : allAuths) {
            Map<String, Object> authTree = new HashMap<>();
            authTree.put("id", one.getId());
            authTree.put("name", one.getMenuName() + " " + StringUtil.getStr(one.getPermission()));
            authTree.put("pId", one.getParentId());
            authTree.put("open", true);
            authTree.put("checked", false);
            for (SysMenu temp : roleAuths) {
                if (temp.getId().equals(one.getId())) {
                    authTree.put("checked", true);
                    break;
                }
            }
            authTrees.add(authTree);
        }
        return authTrees;
    }

    /**
     * 修改角色权限
     */
    @RequiresPermissions("role:update")
    @ResponseBody
    @PostMapping("/updateRoleAuth")
    public JsonResult updateRoleAuth(Integer roleId, String authIds,HttpServletRequest request) {
        if (roleMenuService.updateRoleAuth(roleId, JSONUtil.parseArray(authIds, Integer.class))) {
            commonService.saveOperation(request,"角色管理-权限分配");
            return ok("修改成功");
        }
        return error("修改失败");
    }
}
